package sample.ws.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sample.ws.entity.CommonRepository;
import sample.ws.entity.ServiceEntity;
import sample.ws.entity.ServiceRepository;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * CacheUtils..
 *
 * @author Lizhong
 * @date 2019/7/18
 */
@Component
public class LocalCacheUtils {
    @Autowired
    ServiceRepository serviceRepository;

    @Autowired
    CommonRepository commonRepository;

    public static Map<Long, List<String>> columnsCache = new ConcurrentHashMap<>();
    public static Map<Long, String> sqlCache = new ConcurrentHashMap<>();

    public void updateSqlCache(ServiceEntity serviceEntity) {
        if (serviceEntity != null) {
            sqlCache.put(serviceEntity.getId(), createSql(serviceEntity));
            return;
        }
    }

    @PostConstruct
    void initSqlCache() {
        List<ServiceEntity> serviceEntities = serviceRepository.findAllByEnableIsTrueAndState(1);
        serviceEntities.forEach(val -> sqlCache.put(val.getId(), createSql(val)));
    }

    private String createSql(ServiceEntity val) {
        String tableName = val.getTableName();
        String[] columns = val.getColumns().split(",");

        StringBuffer stringBuffer = new StringBuffer("select ");

        List<String> list = columnsCache.computeIfAbsent(val.getId(), val0 ->(new ArrayList<>()));
        list.add("total");
        for (int i = 0; i < columns.length; i++) {
            stringBuffer.append(columns[i]);
            stringBuffer.append(",");
            if(columns[i].trim().equals("*")) {
                list.addAll( commonRepository.queryTableCloumns(tableName));
                continue;
            }
            list.add(columns[i]);
        }

        stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(","));
        stringBuffer.append(" from (select count(id ) total from ");
        stringBuffer.append(tableName);
        stringBuffer.append(" ) t ,");
        stringBuffer.append(tableName);
        return stringBuffer.toString();
    }
}
